package com.rc.saas.mini.controller.rc;

import com.alibaba.fastjson.JSON;
import com.rc.saas.base.MinipBaseController;
import com.rc.saas.mini.common.base.DataTResponse;
import com.rc.saas.mini.common.mq.MqConfig;
import com.rc.saas.mini.common.mq.MqProducer;
import com.rc.saas.mini.minip.vo.LoginInfoVo;
import com.rc.saas.mini.model.rc.RcChannelApply;
import com.rc.saas.mini.model.rc.RcChannelApplyExample;
import com.rc.saas.mini.model.rc.RcChannelGainRecordExample;
import com.rc.saas.mini.model.rc.RcMsgNotification;
import com.rc.saas.mini.service.rc.RcChannelApplyService;
import com.rc.saas.mini.service.rc.RcChannelGainRecordService;
import com.rc.saas.mini.service.rc.RcMsgNotificationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Description
 * @Author
 * @Date: 2022-06-02
 */

@Api(tags = "24.渠道商申请")
@Controller
@RequestMapping("/rcChannelApply")
public class RcChannelApplyController extends MinipBaseController {

    private static Logger logger = LogManager.getLogger(RcChannelApplyController.class);

    @Autowired
    private RcChannelApplyService rcChannelApplyService;

    @Autowired
    private RcChannelGainRecordService channelGainRecordService;

    @Autowired
    private MqProducer mqProducer;

    @Autowired
    private RcMsgNotificationService rcMsgNotificationService;

    /**
     * 增、改
     */
    @ApiOperation(value = "申请渠道商", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/saveRcChannelApply", method = RequestMethod.POST)
    @ResponseBody
    private DataTResponse<String> saveRcChannelApply(HttpServletRequest request, RcChannelApply rcChannelApply) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null || loginInfo.getMemberId() == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        RcChannelApplyExample example = new RcChannelApplyExample();
        example.createCriteria().andMemberIdEqualTo(loginInfo.getMemberId());
        example.setOrderByClause("last_updated_time desc,created_time desc");
        List<RcChannelApply> oldList = rcChannelApplyService.selectByExample(example);
        //判断是否重复申请
        if (!CollectionUtils.isEmpty(oldList)
                && oldList.stream().filter(data -> "0".equals(data.getStatus()) || "1".equals(data.getStatus())).findFirst().orElseGet(() -> null) != null) {
            return DataTResponse.FAIL("用户已申请!");
        }
        //判断是否已认证
        RcChannelGainRecordExample gainRecordExample = new RcChannelGainRecordExample();
        gainRecordExample.createCriteria().andMemberIdEqualTo(loginInfo.getMemberId()).andStatusEqualTo("0");
        Long count = channelGainRecordService.countByExample(gainRecordExample);
        if(count>0){
            return DataTResponse.FAIL("该用户已认证!");
        }

        rcChannelApply.setMemberId(loginInfo.getMemberId());
        rcChannelApply.setPrincipal(rcChannelApply.getPrincipal()!=null?rcChannelApply.getPrincipal():loginInfo.getNickname());
        rcChannelApply.setChannelApplyId(null);
        rcChannelApply.setCreatedTime(new Date());
        rcChannelApply.setStatus("0");
        rcChannelApply.setCreatedBy(loginInfo.getMemberId() + "");
        rcChannelApplyService.insertByReturnId(rcChannelApply);

        HashMap<String, Long> map = new HashMap<>();
        map.put("channelApplyId", rcChannelApply.getChannelApplyId());
        // 发送mq 给后台
        mqProducer.send(MqConfig.platform_apply, JSON.toJSONString(map));
        RcMsgNotification rcMsgNotification=new RcMsgNotification();
        rcMsgNotification.setTenantCode(loginInfo.getTenantCode());
        rcMsgNotification.setMsgType("2");
        rcMsgNotification.setMsgId(rcChannelApply.getChannelApplyId().toString());
        rcMsgNotificationService.saveRcMsgNotification(rcMsgNotification);
        return DataTResponse.SUCCESS();
    }

    /**
     * 查询
     */
    @ApiOperation("查询单个 渠道商申请")
    @RequestMapping(value = "/selectByChannelApplyId", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "channelApplyId", paramType = "query", value = "加盟商申请id", required = false)})
    private DataTResponse<RcChannelApply> selectByChannelApplyId(HttpServletRequest request, Long channelApplyId) {
        LoginInfoVo loginInfoVo = readLoginInfo(request);
        if (loginInfoVo == null || loginInfoVo.getMemberId() == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        RcChannelApply rcChannelApply = rcChannelApplyService.selectByPrimaryKey(channelApplyId);
        if (!loginInfoVo.getMemberId().equals(rcChannelApply.getMemberId())) {
            rcChannelApply = null;
        }
        return DataTResponse.SUCCESS_DATA(rcChannelApply);
    }

    /**
     * 查询列表
     */
    @ApiOperation("查询列表 渠道商列表")
    @RequestMapping(value = "/listByRcChannelApply", method = RequestMethod.POST)
    @ResponseBody
    private DataTResponse<List<RcChannelApply>> listByRcChannelApply(HttpServletRequest request, RcChannelApply rcChannelApply) {
        LoginInfoVo loginInfoVo = readLoginInfo(request);
        if (loginInfoVo == null || loginInfoVo.getMemberId() == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        List<RcChannelApply> list = rcChannelApplyService.listByCondition(rcChannelApply);
        return DataTResponse.SUCCESS_DATA(list);
    }

    ///**
    // * 查询列表分页
    // */
    //@ApiOperation("查询列表分页 渠道商申请")
    //@RequestMapping(value = "/listPageByRcChannelApply", method = RequestMethod.POST)
    //@ResponseBody
    //private TResponse listPageByRcChannelApply(@ApiIgnore HttpSession session, RcChannelApply rcChannelApply, LkPageVo lkPageVo) {
    //    //Page
    //    PageHelper.startPage(lkPageVo.getPageNo(), lkPageVo.getPageSize());
    //    List<RcChannelApply> list = rcChannelApplyService.listByCondition(rcChannelApply);
    //    PageInfo<RcChannelApply> pageInfo = new PageInfo<>(list);
    //    return TResponse.SUCCESS_DATA(pageInfo);
    //}
}
